package com.koo.common.utils.file;

import com.koo.common.utils.MyStrUtil;
import com.koo.common.utils.PropFileConfig;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

/**
 * 文件上传
 *
 * @author charlin
 */
public class UploadUtil {

    private static final int TIME_OUT = 10 * 10000000; // 超时时间
    private static final String CHARSET = "utf-8"; // 设置编码  
    public static final String SUCCESS = "1";
    public static final String FAILURE = "0";

    /**
     * 文件上传
     * 1)设置文件格式
     * 2)创建连接
     * 3)写数据
     * 4)输出数据
     * @param file
     * @param RequestURL
     * @return
     */
    public static String uploadFileByHttpUrl(File file, String RequestURL) {
        String BOUNDARY = UUID.randomUUID().toString(); // 边界标识 随机生成  
        String PREFIX = "--", LINE_END = "\r\n";
        String CONTENT_TYPE = "multipart/form-data"; // 内容类型
        OutputStream outputSteam = null;
        DataOutputStream dos = null;
        try {
            URL url = new URL(RequestURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(TIME_OUT);
            conn.setConnectTimeout(TIME_OUT);
            conn.setDoInput(true); // 允许输入流  
            conn.setDoOutput(true); // 允许输出流  
            conn.setUseCaches(false); // 不允许使用缓存  
            conn.setRequestMethod("POST"); // 请求方式  
            conn.setRequestProperty("Charset", CHARSET); // 设置编码  
            conn.setRequestProperty("connection", "keep-alive");
            conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
            if (file != null) {
                //当文件不为空，把文件包装并且上传
                outputSteam = conn.getOutputStream();
                dos = new DataOutputStream(outputSteam);
                StringBuffer sb = new StringBuffer();
                sb.append(PREFIX);
                sb.append(BOUNDARY);
                sb.append(LINE_END);
                /**
                 * 这里重点注意： name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件 
                 * filename是文件的名字，包含后缀名的 比如:abc.png 
                 */
                sb.append("Content-Disposition: form-data; name=\"img\"; filename=\"" + file.getName() + "\"" + LINE_END);
                sb.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINE_END);
                sb.append(LINE_END);
                dos.write(sb.toString().getBytes());
                InputStream is = new FileInputStream(file);
                byte[] bytes = new byte[1024];
                int len = 0;
                while ((len = is.read(bytes)) != -1) {
                    dos.write(bytes, 0, len);
                }
                is.close();
                dos.write(LINE_END.getBytes());
                byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();
                dos.write(end_data);
                dos.flush();
                /**
                 * 获取响应码 200=成功 当响应成功，获取响应的流 
                 */
                int res = conn.getResponseCode();
                if (res == 200) {
                    //得到响应流
                    InputStream inputStream = conn.getInputStream();
                    //获取响应
                    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                    String line;
                    StringBuffer resutl = new StringBuffer();
                    while ((line = reader.readLine()) != null){
                        resutl.append(line);
                    }
                    reader.close();
                    conn.disconnect();
                    //该干的都干完了,
                    return resutl.toString();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                dos.close();
                outputSteam.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return FAILURE;
    }


    /**
     * 使用httpClient的post方法上传
     *
     * @param file 上传文件
     */
    public static String uploadFileByHttpClient(File file, String requestUrl) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        String result = "";
        try {
            httpClient = HttpClients.createDefault();
            // 把一个普通参数和文件上传给下面这个地址 是一个servlet
            HttpPost httpPost = new HttpPost(requestUrl);
            // 把文件转换成流对象FileBody
            FileBody fileBody = new FileBody(file);
//            StringBody userName = new StringBody("Scott", ContentType.create(
//                    "text/plain", Consts.UTF_8));
//            StringBody password = new StringBody("123456", ContentType.create(
//                    "text/plain", Consts.UTF_8));
            HttpEntity reqEntity = MultipartEntityBuilder.create()
                    // 相当于<input type="file" name="file"/>
                    .addPart("file", fileBody)
                    // 相当于<input type="text" name="userName" value=userName>
//                    .addPart("userName", userName)
//                    .addPart("pass", password)
                    .build();
            httpPost.setEntity(reqEntity);
            // 发起请求 并返回请求的响应
            response = httpClient.execute(httpPost);
            // 获取响应对象
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                // 打印响应内容
                result = EntityUtils.toString(resEntity, Charset.forName("UTF-8"));
            }
            // 销毁
            EntityUtils.consume(resEntity);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 将文件提交至文件服务器
     *
     * @param file 文件对象
     * @return FileStatus 上传结果
     */
    public static String postFile(File file, String requestUrl, String filename) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String result = null;
        try {
            HttpPost httpPost = new HttpPost(requestUrl);
            MultipartEntityBuilder mEntityBuilder = MultipartEntityBuilder.create();
            //mEntityBuilder.addBinaryBody("file", file);
            InputStream inputStream = new FileInputStream(file);
            mEntityBuilder.addBinaryBody("file", inputStream, ContentType.MULTIPART_FORM_DATA, filename);
            httpPost.setEntity(mEntityBuilder.build());
            response = httpclient.execute(httpPost);

            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                HttpEntity resEntity = response.getEntity();
                result = EntityUtils.toString(resEntity);
                // 消耗掉response
                EntityUtils.consume(resEntity);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            HttpClientUtils.closeQuietly(httpclient);
            HttpClientUtils.closeQuietly(response);
        }
        return result;
    }

    /**
     * 文件上传
     * @param filename
     * @return
     */
    public static String uploadFile(String filename){
        File file = new File(filename);
        String IMAGE_PATH =  PropFileConfig.getProperty("file.host");
        String filestrExt = filename.substring(filename.lastIndexOf("."));
        filename = MyStrUtil.generate16ShortUUID() + filestrExt;
        String url = IMAGE_PATH + "uploadFile?filename=" +filename;
        String result = UploadUtil.postFile(file, url, filename);
        file.deleteOnExit();
        return IMAGE_PATH + "/upload/" + result ;
    }


    public static File getFile(CommonsMultipartFile cmfFile) {
        CommonsMultipartFile commonsMultipartFile = (CommonsMultipartFile) cmfFile;
        DiskFileItem diskFileItem = (DiskFileItem) commonsMultipartFile.getFileItem();
        File file = diskFileItem.getStoreLocation();
        return file;
    }


    public static HttpEntity makeMultipartEntity(List<NameValuePair> params, final Map<String, File> files) {
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); //如果有SocketTimeoutException等情况，可修改这个枚举
        //builder.setCharset(Charset.forName("UTF-8")); //不要用这个，会导致服务端接收不到参数
        if (params != null && params.size() > 0) {
            for (NameValuePair p : params) {
                builder.addTextBody(p.getName(), p.getValue(), ContentType.TEXT_PLAIN.withCharset("UTF-8"));
            }
        }
        if (files != null && files.size() > 0) {
            Set<Map.Entry<String, File>> entries = files.entrySet();
            for (Map.Entry<String, File> entry : entries) {
                builder.addPart(entry.getKey(), new FileBody(entry.getValue()));
            }
        }
        return builder.build();
    }


}